// n choose k?


var threeSumClosest = function (nums: number[], target: number) {

    let ans: number[] = []
    let container: number[] = []

    function sum(a: number[]): number {
        if (a.length === 0) return Number.MAX_SAFE_INTEGER

        return a.reduce((s, a) => s + a)
    }


    const diff = (a: number[]) => {
        return Math.abs(sum(a) - target)
    }

    function search(from: number) {

        if (diff(ans) === 0) return

        if (container.length === 3) {

            if (diff(container) < diff(ans)) {
                ans = container.slice()
            }
            return
        }

        if (from >= nums.length) {
            return
        }

        container.push(nums[from])
        search(from + 1)

        container.pop()
        search(from + 1)
    }

    search(0)

    return sum(ans)
};


// console.log(threeSumClosest([-1, 2, 1, 4], 1));